#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
import json
import socket
import os
import time
from conf import  setting
os.chdir(os.pardir)
server_address = (setting.FTP_HOST,setting.FTP_PORT)
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(server_address)

while True:
    cmd = input(">>>").strip()
    if len(cmd) == 0:
        continue
    cmd_list = cmd.split()
    #
    #上传文件
    if cmd_list[0] == 'put':
        if len(cmd_list) == 1:
            print('请输入文件名！')
            continue
        filename = cmd_list[1]
        if os.path.isfile(filename):
            file_obj = open(filename,'rb')
            base_filename = os.path.basename(filename) #获取文件名
            print(base_filename, os.path.getsize(filename))
            data_header = {
                'action':'put',
                'filename':base_filename,
                'size':os.path.getsize(filename)
            }
            sock.send(json.dumps(data_header).encode()) #发送操作信息给服务器端
            send_back = sock.recv(1)
            print(send_back)
            send_size = 0
            while send_size < data_header['size']:
                data = file_obj.read(setting.read_size)
                sock.sendall(data)
                send_size +=len(data)
                #print(send_size)
            else:

                print('----send file done----')
        else:
            print('File is not valid')
            continue
    #
    # 下载文件
    elif cmd_list[0] == 'get':
        if len(cmd_list) == 3:
            filename = cmd_list[1] #获取需要下载的文件名
            print(filename)
            save_path = cmd_list[2] #获取需要存放的本地文件路径
            print(save_path)
            save_file=os.path.join(save_path,filename) #拼凑下载到本地的完整文件路径
            print(save_file)
            if os.path.isdir(save_path):
                if os.path.isfile(save_file) is not True:
                    data_header = {
                        'action': 'get',
                        'filename': filename
                    }
                    sock.send(json.dumps(data_header).encode())
                    file_size = sock.recv(1024)
                    file_size_1=file_size.decode()
                    print(file_size_1)
                    file_obj = open(save_file, 'wb')
                    received_size = 0
                    while received_size < int(file_size_1):
                            recv_data = sock.recv(4096)
                            file_obj.write(recv_data)
                            received_size += len(recv_data)
                            #print(received_size)
                    else:
                        print('Successfully received file ',save_file)
                        file_obj.close()

    else:
        print('输入错误！')
